package com.suep.game_chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suep.game_chat.dto.UserDTO;
import com.suep.game_chat.entity.User;
import com.suep.game_chat.mapper.UserMapper;
import com.suep.game_chat.service.UserService;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    @Transactional
    public User register(UserDTO user) {
        // 检查用户名是否已存在
        if (lambdaQuery().eq(User::getUsername, user.getUsername()).exists()) {
            throw new RuntimeException("用户名已存在");
        }
        User user1 = new User();
        user1.setUserId(String.valueOf(System.currentTimeMillis()));
        user1.setUsername(user.getUsername());
        user1.setPassword(user.getPassword());
        user1.setNickname(user.getNickname());
        user1.setAvatar(user.getAvatar());
        user1.setGender(user.getGender());
        user1.setPhone(user.getPhone());
        user1.setEmail(user.getEmail());
        user1.setGameUid(user.getGameUid());
        // 保存用户
        save(user1);
        return user1;
    }

    @Override
    public User login(String username, String password) {
        User user = lambdaQuery()
                .eq(User::getUsername, username)
                .eq(User::getPassword, password)
                .one();
                
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        return user;
    }

    @Override
    @Transactional
    public void updatePassword(String userId, String oldPassword, String newPassword) {
        User user = getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (!user.getPassword().equals(oldPassword)) {
            throw new RuntimeException("原密码错误");
        }
        
        user.setPassword(newPassword);
        updateById(user);
    }
} 